package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.MajorQueryRequest;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.entity.Major;
import com.pn.taikao.service.MajorService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/majors")
public class MajorController {

    private final MajorService majorService;

    public MajorController(MajorService majorService) {
        this.majorService = majorService;
    }

    /**
     * 创建专业
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<CreateResponse> create(@RequestBody Major major) {
        Long id = majorService.createMajor(major);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新专业
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody Major major) {
        major.setId(id);
        majorService.updateMajor(major);
        return ApiResponse.success(null);
    }

    /**
     * 删除专业
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        majorService.deleteMajor(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询专业详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<Major> detail(@PathVariable("id") Long id) {
        Major major = majorService.getById(id);
        if (major == null) {
            return ApiResponse.error("专业不存在");
        }
        return ApiResponse.success(major);
    }

    /**
     * 根据学院ID获取专业列表（不分页，用于下拉选择）
     */
    @GetMapping("/college/{collegeId}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<List<Major>> getByCollege(@PathVariable("collegeId") Long collegeId) {
        List<Major> majors = majorService.getByCollegeId(collegeId);
        return ApiResponse.success(majors);
    }

    /**
     * 分页查询专业列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<Major>> list(@RequestBody MajorQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        List<Major> data = majorService.list(request.getName(), request.getCollegeId(), page, size);
        long total = majorService.count(request.getName(), request.getCollegeId());
        PageResult<Major> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}











